import { useState, useEffect } from "react";

import { Form, Table, Button, Input, DatePicker, TimePicker, Popconfirm, message } from "antd";
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";

import { UserSearchResult } from "../user";
import { MeetingRoomSearchResult } from "../meeting-room";

import { getBookingList, apply, reject, unbind } from "../../api/booking";

import "./booking-manage.css";

import dayjs from "dayjs"

/* 一些可以不写在函数式组件内的变量和方法 */
export interface SearchBooking {
    username: string;
    meetingRoomName: string;
    meetingRoomPosition: string;
    rangeStartDate: Date;
    rangeStartTime: Date;
    rangeEndDate: Date;
    rangeEndTime: Date;
}

interface BookingSearchResult {
    id: number;
    startTime: string;
    endTime: string;
    status: string;
    note: string;
    createTime: string;
    updateTime: string;
    user: UserSearchResult;
    room: MeetingRoomSearchResult;
}


export function BookingManage() {
    /* state变量书写区 */ 
    const [pageNo, setPageNo] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [bookingSearchResult, setBookingSearchResult] = useState<Array<BookingSearchResult>>([]);
    const [assistVar, setAssistVar] = useState<number>(0); // 借助辅助变量，实现删除，新增等一些操作后刷新列表
    /* 非state变量书写区 */ 
    const [form] = useForm();
    const columns: ColumnsType<BookingSearchResult> = [
        {
            title: "会议室名称",
            dataIndex: "room",
            render(_, record) {
                return record.room.name
            }
        },
        {
            title: "会议室位置",
            dataIndex: "room",
            render(_, record) {
                return record.room.location
            }
        },
        {
            title: "预定人",
            dataIndex: "user",
            render(_, record) {
                return record.user.username
            }
        },
        {
            title: "开始时间",
            dataIndex: "startTime",
            render(_, record) {
                return dayjs(new Date(record.startTime)).format("YYYY-MM-DD HH:mm:ss")
            }
        },
        {
            title: "结束时间",
            dataIndex: "endTime",
            render(_, record) {
                return dayjs(new Date(record.endTime)).format("YYYY-MM-DD HH:mm:ss")
            }
        },
        {
            title: "审批状态",
            dataIndex: "status",
            filters: [
                {
                    text: "审批通过",
                    value: "审批通过"
                },
                {
                    text: "审批驳回",
                    value: "审批驳回"
                },
                {
                    text: "申请中",
                    value: "申请中"
                },
                {
                    text: "已解除",
                    value: "已解除"
                }
            ],
            onFilter: (value, record) => record.status.startsWith(value as string)
        },
        {
            title: "预定时间",
            dataIndex: "createTime",
            render(_, record) { // 如果没有render则直接渲染 datasource中对应的 dataIndex数据，如果有render则优先按照render函数返回的渲染显示
                return dayjs(new Date(record.createTime)).format("YYYY-MM-DD HH:mm:ss")
            }
        },
        {
            title: "备注",
            dataIndex: "note"
        },
        {
            title: "描述",
            dataIndex: "description"
        },
        {
            title: "操作",
            render: (_, record)=> (
                <div>
                    <Popconfirm 
                        title="通过申请"
                        description="确认通过吗？"
                        onConfirm={()=>{changeStatus(record.id, 'apply')}}
                        okText="确定"
                        cancelText="取消">
                            <a href="#">通过</a>
                    </Popconfirm>
                    <Popconfirm 
                        title="驳回申请"
                        description="确认驳回申请吗？"
                        onConfirm={()=>{changeStatus(record.id, 'reject')}}
                        okText="确定"
                        cancelText="取消">
                            <a href="#">驳回</a>
                    </Popconfirm>
                    <Popconfirm 
                        title="解除申请"
                        description="确认解除申请吗？"
                        onConfirm={()=>{changeStatus(record.id, 'unbind')}}
                        okText="确定"
                        cancelText="取消">
                            <a href="#">解除</a>
                    </Popconfirm>
                </div>
            )
        }
    ]
    /* 方法书写区 */ 
    const changePage = (pageNo: number, pageSize: number)=>{
        setPageNo(pageNo);
        setPageSize(pageSize);
    }
    const searchBooking = async (values: SearchBooking)=>{
        const { data: { bookings }, status } = await getBookingList(values, pageNo, pageSize);
        if (status === 201 || status === 200) {
            setBookingSearchResult(bookings.map((item: BookingSearchResult) => {
                return {
                    key: item.id,
                    ...item
                }
            }));
        }else {
            message.error("系统繁忙，请稍后重试");
        }
    }
    const changeStatus = async (id: number, status: 'apply'|'reject'|'unbind')=>{
        const api = {
            apply,
            reject,
            unbind
        }

        const { status:code } = await api[status](id);
        if(code === 201 || code === 200) {
            message.success("状态更新成功");
            setAssistVar(Math.random());
        }else {
            message.error("更新失败，请稍后重试");
        }
    }
    /* 生命周期书写区 */ 
    // 传入useEffect的函数是不可以被async await修饰的，如果需要异步操作可以重新写一个函数在useEffect中调用
    useEffect(()=>{
        searchBooking({
            username: form.getFieldValue("username"),
            meetingRoomName: form.getFieldValue("meetingRoomName"),
            meetingRoomPosition: form.getFieldValue('meetingRoomPosition'),
            rangeStartDate: form.getFieldValue("rangeStartDate"),
            rangeStartTime: form.getFieldValue("rangeStartTime"),
            rangeEndDate: form.getFieldValue("rangeEndDate"),
            rangeEndTime: form.getFieldValue("rangeEndTime")
        });
    }, [pageNo, pageSize])
    /* DOM结构书写区 */ 
    return (
        <div className="booking-manager">
            <div className="booking-manage__form">
                <Form 
                    name="search"
                    layout="inline"
                    colon={false}
                    form={form}
                    onFinish={searchBooking} >
                    <Form.Item label="预定人" name="username">
                        <Input />
                    </Form.Item>
                    <Form.Item label="会议室名称" name="meetingRoomName">
                        <Input />
                    </Form.Item>
                    <Form.Item label="预定开始日期" name="rangeStartDate">
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="预定开始时间" name="rangeStartTime">
                        <TimePicker />
                    </Form.Item>
                    <Form.Item label="预定结束日期" name="rangeEndDate">
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="预定结束时间" name="rangeEndTime">
                        <TimePicker />
                    </Form.Item>
                    <Form.Item label="位置" name="meetingRoomPosition">
                        <Input />
                    </Form.Item>

                    <Form.Item label=" ">
                        <Button type="primary" htmlType="submit">搜索预定申请</Button>
                    </Form.Item>
                </Form>
            </div>
            <div className="booking-manager__table">
                <Table columns={columns} dataSource={bookingSearchResult} pagination={{
                    current: pageNo,
                    pageSize: pageSize,
                    onChange: changePage
                }} />
            </div>
        </div>
    )
}